'use strict';
import React from 'react';
import { StyleSheet, Image, } from 'react-native';
import PropTypes from 'prop-types'
import FastImage from 'react-native-fast-image'

class ImageView extends React.PureComponent {

    static propTypes = {
        ...Image.propTypes,
        useFastImage: PropTypes.bool, // 使用原生桥接的缓存image 
        maxImageWidth: PropTypes.number,

    };

    static defaultProps = {
        ...Image.defaultProps,
        useFastImage: true,
        resizeMode: 'contain',
    };

    constructor(props) {
        super(props);
        this.state = { imageSize: null }
    };

    componentDidMount() {

    }

    componentWillUnmount() {

    }

    _setImageSize = (width, height) => {
        const { maxImageWidth } = this.props
        if (width >= maxImageWidth) {
            height = (maxImageWidth / width) * height
            width = maxImageWidth
        }
        this.setState({ imageSize: { width, height } })
    };

    _onImageLoad = (event) => {
        // console.log('_onImageLoad', event.nativeEvent)
        const { maxImageWidth, onLoad } = this.props;
        const { width, height, source } = event.nativeEvent;
        if (maxImageWidth) {
            if (source) {
                this._setImageSize(source.width, source.height)
            } else if (width && height) {
                this._setImageSize(width, height)
            }
        }
        onLoad && onLoad(event)
    };

    renderImageView = () => {
        const { useFastImage, style, source, onLoad, tintColor, ...others } = this.props;
        const { imageSize } = this.state;
        if (useFastImage && source && typeof source !== 'number' && source.uri) {
            if (typeof source.uri === 'string' && !source.uri.startsWith('http')) {
                source.uri = `${ServicesApi.QI_NIU_LINK}${source.uri}`;
            }
            return (
                <FastImage
                    style={[style, imageSize]}
                    source={{ priority: 'low', ...source }}
                    onLoad={this._onImageLoad}
                    {...others}
                />
            )
        } else if (!useFastImage || typeof source === 'number') {
            return (
                <Image
                    style={[style, imageSize, {tintColor: tintColor}]}
                    source={source}
                    onLoad={this._onImageLoad}
                    {...others}
                />
            )
        }
        if (__DEV__ && !source) {
            console.warn('source不能为空')
        }
        if (__DEV__ && source && !source.uri) {
            console.warn('uri不能为空')
        }
        return null
    };

    render() {
        return this.renderImageView()
    }
}


const styles = StyleSheet.create({

});

export default ImageView;
